package com.liujian.gymxmjpa.fontconntroller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.liujian.gymxmjpa.utils.R;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController()
@CrossOrigin(origins = "*",allowCredentials = "true")
@RequestMapping("/aliyun")
public class AliyunController {

    @Resource
    RedisTemplate redisTemplate;

    @RequestMapping("/send")
    public R sendMessages(){
        DefaultProfile profile = DefaultProfile.getProfile("cn-shenzhen"
                , ""
                , "");
        IAcsClient client = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers("");//接收短信的手机号码
        request.setSignName("阿里云短信测试");//短信签名名称
        request.setTemplateCode("SMS_154950909");//短信模板CODE
        String code ="1234";
        request.setTemplateParam("{\"code\":\""+code+"\"}");//短信模板变量对应的实际值
        //判断5分钟内是否已经发送过验证码
        Object yzm =  redisTemplate.opsForValue().get("");
        if(yzm!=null){
            return R.ok().put("data",yzm);
        }
        //发送验证码
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            //存入Redis
            redisTemplate.opsForValue().set("", code);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return R.ok().put("data",code);
    }
}
